﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WFNetLib.NMEA;

namespace RobotControl
{
    public partial class Form_CLJTL : Form
    {
        public Form_CLJTL()
        {
            InitializeComponent();
        }
        private bool ComListening = false;//是否没有执行完invoke相关操作              
        private bool ComClosing = false;//是否正在关闭串口，执行Application.DoEvents， 并阻止再次invoke 
        HCHDT hchdt = new HCHDT();
        private void Form_CLJTL_Load(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = Properties.Settings.Default.磁罗经通道;
                serialPort1.Open();
            }
            catch 
            { 
                MessageBox.Show("磁力仪对应串口无法打开，无法进行磁罗经调零!");
                this.Close();
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            char rx;
            if (ComClosing)
                return;
            ComListening = true;
            while (serialPort1.BytesToRead != 0)
            {
                int irx = serialPort1.ReadByte();
                if (irx == -1)
                    break;
                rx = (char)irx;
                if (hchdt.RxProc(rx))
                {
                    //ExternAddText("收到磁罗经数据:\r\n" + hchdt.AllRx);
                    this.Invoke((EventHandler)(delegate
                    {
                        textBox1.AppendText(hchdt.AllRx+"\r\n");
                    }));
                    if (hchdt.True == "T")
                    {
                        meter1.Value = Convert.ToDouble(hchdt.Heading);
                    }
                }
            }
            ComListening = false;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                Properties.Settings.Default.磁罗经修正角度 = Convert.ToDouble(hchdt.Heading);
                Properties.Settings.Default.Save();
                MessageBox.Show("设定磁罗经零角度成功!");
                this.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }            
        }

        private void Form_CLJTL_FormClosing(object sender, FormClosingEventArgs e)
        {
            ComClosing = true;
            while (ComListening)
                Application.DoEvents();
            serialPort1.Close();
        }
    }
}
